package com.mgm.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.transfer.TransferManager;

public class AwsClient {
	
	private static Logger logger =LoggerFactory.getLogger(AwsClient.class);
	
	static AmazonS3 s3client;
	static TransferManager tx;
	private static String AWS_ACCESS_KEY = "AKIAJQ4UICW76VGXMNUA";
	private static String AWS_SECRET_KEY = "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";
	static final String bucketName = "project.public.test"; //默认bucket

	/** Creating Client Connection.*/
	static {
		AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY); //创建凭证
		s3client = AmazonS3ClientBuilder
			.standard()
			.withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(Regions.AP_NORTHEAST_1)
			.build();
	}
	
	/**
	 * 创建Bucket
	 * @Title: createBucket   
	 * @Description: TODO(...)   
	 * @param: @param bucketName      
	 * @return: void      
	 * @throws
	 */
	public static void createBucket(String bucketName) {
		if(s3client.doesBucketExistV2(bucketName)) { //存在bucket
			logger.info("Bucket name is not available."
		      + " Try again with a different Bucket name.");
		    return;
		}
		s3client.createBucket(bucketName);
	}

	/**
	 * 将文件上传至S3上并且返回带签名url 
	 * @Title: uploadToS3
	 * @Description: 将文件上传至S3上并且返回带签名url 
	 * @param tempFile 目标文件 
	 * @param key 文件名
	 * @throws IOException 设定文件 
	 * @return String 返回类型 
	 */
	public static String uploadToS3(String key, File file) throws IOException {
		try {
			// 上传文件
			s3client.putObject(new PutObjectRequest(bucketName, key, file)
					.withCannedAcl(CannedAccessControlList.PublicRead));
			// 获取一个request
			GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
			// 生成公用的url
			URL url = s3client.generatePresignedUrl(urlRequest);
			return url.toString();
		} catch (AmazonServiceException ase) {
			ase.printStackTrace();
		} catch (AmazonClientException ace) {
			ace.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: uploadToS3V2   
	 * @Description: TODO(...)   
	 * @param: @param file
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String uploadToS3V2(File file) {
		// 上传文件
		String key = System.currentTimeMillis()+"_"+file.getName();
		s3client.putObject(new PutObjectRequest(bucketName, key, file)
				.withCannedAcl(CannedAccessControlList.PublicRead));
		return s3client.getUrl(bucketName, key).toString();
	}
	/**
	 * @Title: getContentFromS3 
	 * @Description: 获取文件2进制流 
	 * @param key 
	 * @throws IOException  
	 * @return S3ObjectInputStream
	 */
	public static S3ObjectInputStream getContentFromS3(String key) throws IOException {
		try {
			GetObjectRequest request = new GetObjectRequest(bucketName, key);
			S3Object object = s3client.getObject(request);
			S3ObjectInputStream inputStream = object.getObjectContent();
			return inputStream;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @Title: downFromS3 
	 * @Description: 将文件下载到本地路径
	 * @param key 文件名 
	 * @param path 下载的路径
	 * @throws
	 */
	public static void downFromS3(String key, String path) throws IOException {
		try {
			GetObjectRequest request = new GetObjectRequest(bucketName, key);
			s3client.getObject(request, new File(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取文件的url
	 * @Title: getUrlFromS3   
	 * @Description: 获取文件的url
	 * @param: @param key
	 * @param: @return
	 * @param: @throws IOException      
	 * @return: String      
	 * @throws
	 */
	public static String getUrlFromS3(String key) throws IOException {
		try {
			GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(bucketName, key);
			String url = s3client.generatePresignedUrl(httpRequest).toString();// 临时链接
			return url;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 验证s3client上是否存在名称为bucketName的Bucket
	 * 
	 * @param s3client
	 * @param bucketName
	 * @return
	 */
	public static boolean checkBucketExists(AmazonS3 s3client, String bucketName) {
		List<Bucket> buckets = s3client.listBuckets();
		for (Bucket bucket : buckets) {
			if (Objects.equals(bucket.getName(), bucketName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 删除S3上文件
	 * @Title: delFromS3   
	 * @Description: TODO(...)   
	 * @param: @param key
	 * @param: @throws IOException      
	 * @return: void      
	 * @throws
	 */
	public static void delFromS3(String key) throws IOException {
		try {
			s3client.deleteObject(bucketName, key);
		} catch (AmazonServiceException ase) {
			ase.printStackTrace();
		} catch (AmazonClientException ace) {
			ace.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		String key = "redisinfo";
		File tempFile = new File("C:\\Users\\Andy\\Pictures\\11.jpg");
		File file = new File("C:\\Users\\Andy\\Pictures\\图片1.JPG");
		File vedio = new File("C:\\Users\\Andy\\Videos\\Video_2018-06-10_212246.wmv");
		String url1 = uploadToS3(tempFile.getName(), tempFile);// 上传文件
		System.out.println(url1);
		String url = getUrlFromS3(key);// 获取文件的url
		System.out.println("临时：" + url);
		System.out.println(s3client.getUrl(bucketName, "11.jpg"));
		// delFromS3(key);//删除文件
		createBucket(bucketName+"1");
		System.out.println("===>"+uploadToS3V2(file));
		System.out.println("===>"+uploadToS3V2(vedio));
	}

}